package com.taotao.rop.manager;

import com.rop.session.Session;
import com.rop.session.SessionManager;
import com.rop.session.SimpleSession;
import com.taotao.rop.database.domain.RopSession;
import com.taotao.rop.database.mapper.RopSessionMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * ROP的会话管理器
 */
public class RopSessionManager implements SessionManager {
    public static final String KEY_SESSION_ID = "sessionID";
    public static final String KEY_MANAGER_ID = "managerID";
    public static final String KEY_ROLE_ID = "roleID";
    public static final String KEY_APP_ID = "appId";
    public static final String KEY_CLIENT_IP = "clientIp";

    @Autowired
    private RopSessionMapper ropSessionMapper;

    @Override
    public void addSession(String sessionId, Session session) {
        RopSession ropSession = new RopSession();
        SimpleSession simpleSession = (SimpleSession)session;
        ropSession.setManagerId((Long) simpleSession.getAttribute(KEY_MANAGER_ID));
        ropSession.setRoleId((Long) simpleSession.getAttribute(KEY_ROLE_ID));
        ropSession.setAppId(String.valueOf(simpleSession.getAttribute(KEY_APP_ID)));
        ropSession.setClientIp(String.valueOf(simpleSession.getAttribute(KEY_CLIENT_IP)));
        List<RopSession> ropSessionList =  ropSessionMapper.getList(ropSession);
        if (ropSessionList != null && ropSessionList.size() == 1){
            ropSessionList.get(0).setSessionId(sessionId);
            ropSessionMapper.updateOne(ropSessionList.get(0));
        } else {
            ropSession.setSessionId(sessionId);
            ropSessionMapper.insertOne(ropSession);
        }
    }

    @Override
    public Session getSession(String sessionId) {
        RopSession condition = new RopSession();
        condition.setSessionId(sessionId);
        List<RopSession> ropSession = ropSessionMapper.getList(condition);
        if (ropSession != null && ropSession.size() > 0) {
            SimpleSession session = new SimpleSession();
            session.setAttribute(KEY_SESSION_ID, sessionId);
            session.setAttribute(KEY_MANAGER_ID, ropSession.get(0).getManagerId());
            session.setAttribute(KEY_ROLE_ID, ropSession.get(0).getRoleId());
            session.setAttribute(KEY_APP_ID, ropSession.get(0).getAppId());
            return session;
        }
        return null;
    }

    @Override
    public void removeSession(String sessionId) {
        ropSessionMapper.removeSession(sessionId);
    }
}
